//
//  CurrentInidentHeaderView.m
//  Runone
//
//  Created by runone02 on 16/12/7.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "CurrentInidentHeaderView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "Masonry.h"
#import "Define.h"
#import "AppConstants.h"
#import "AppDelegate.h"
#import "PileInfo.h"
#import "CustomAnnotationView.h"
#import "CustomCallOutView.h"
#import "ROPointAnnotation.h"
#import "RightCodeTool.h"
#import "OneConst.h"
#import "HighwayMergeInfoModel.h"
#import "StationModel.h"
#import "NSDate+ROCaculateTime.h"
#import "NSDate+Addition.h"

#define      kScrrenW      [UIScreen mainScreen].bounds.size.width

@interface CurrentInidentHeaderView () <MAMapViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *mapBackGroundView;
@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageV;
@property (weak, nonatomic) IBOutlet UILabel *pileNOLabel;
@property (weak, nonatomic) IBOutlet UILabel *directionLabel;
@property (weak, nonatomic) IBOutlet UILabel *beginTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *lastTimeLabel;



@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cameraGunWidth;

@property (nonatomic,strong)NSMutableArray *annotationsArray;

@property (nonatomic, strong)DeviceBaseInfo *minDistanceCamera;//最近的摄像枪model

@end


@implementation CurrentInidentHeaderView

#pragma   ----------- 事故事件详情

- (IBAction)trafficBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _mapView.showTraffic=YES;
    } else {
        _mapView.showTraffic=NO;
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor  = [UIColor colorWithRed:244.0/255 green:244.0/255 blue:244.0/255 alpha:1];
    _mapView.delegate     = self;
    _mapView.showsCompass = NO;
    _mapView.showsScale   = NO;
    _iconImageV.image        = [UIImage imageNamed:@"event_accident_icon"];
    [self configTextColor];
    _cameraArray = [[NSMutableArray alloc] init];
}

- (void) configTextColor {
    _pileNOLabel.textColor    = kTableViewCellTextColor;
    _directionLabel.textColor = kTableViewCellTextColor;
    _beginTimeLabel.textColor = kTableViewCellTextColor;
    _lastTimeLabel.textColor  = kTableViewCellTextColor;
}

//设置模型
- (void) setCeModel:(CurrentEvent *)ceModel {
    _ceModel = ceModel;
    
    if ([_ceModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        _pileNOLabel.text    = [NSString stringWithFormat:@"%@+%@",_ceModel.BeginPile,_ceModel.BeginPileDistance];
    }else {
        NSString *lStr  = @"L";
        NSString *lKStr = [lStr stringByAppendingString:_ceModel.BeginPile];
        _pileNOLabel.text    = [NSString stringWithFormat:@"%@+%@",lKStr,_ceModel.BeginPileDistance];
    }
    
    //    if (_ceModel.BeginPile) {
    
    //    }
    
    [self loadEventAnnotation];
    //    [self getTheWantCameraGun];
    [self gerAllTheDirectionCameraArray];
    [self getMostLeastCameraGun];
    [self configToolView];
}

//- (void)getTheWantCameraGun {
//
//    if ([_ceModel.RoadDerection integerValue] == 1) { //上行
//        _cameraArray = [self getTheWantCameraDevice:_ceModel.RoadDerection ];
//    }
//
//    if ([_ceModel.RoadDerection integerValue] == 2) { // 下行
//        _cameraArray = [self getTheWantCameraDevice:_ceModel.RoadDerection];
//    }
//
//    if ([_ceModel.RoadDerection integerValue] == 3) { //双向
//        _cameraArray = [self  getAllCameraGun];
//    }
//}
- (void) gerAllTheDirectionCameraArray {
    [_cameraArray removeAllObjects];
    
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *model in myDelegate.HighWayRoadArray) {
        if ([model.RoadUID isEqualToString:_ceModel.RoadUID]) {
            _currentRoadModel = model;
        }
    }
    
    if ([_ceModel.RoadDerection integerValue] == RoadTypeUp) {
        for (HighwayMergeInfoModel *mergeInfoModel in _currentRoadModel.mergeInfoList) {
            [self getAllWantCamera:mergeInfoModel.UpWayDevices andDirection:DirectionTypeUp];
        }
    }
    
    if ([_ceModel.RoadDerection integerValue] == RoadTypeDown) {
        for (HighwayMergeInfoModel *mergeInfoModel in _currentRoadModel.mergeInfoList) {
            [self getAllWantCamera:mergeInfoModel.DownWayDevices andDirection:DirectionTypeDown];
        }
    }
    
    //    AppDelegate *myDelegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if ([_ceModel.RoadDerection integerValue] == RoadTypeUpAndDown) {
        for (DeviceBaseInfo *moel in myDelegate.AllDeviceBaseArray) {
            if (moel.DeviceType == DevicesTypeCamera && [moel.RoadUID isEqualToString:_currentRoadModel.RoadUID]) {
                [_cameraArray addObject:moel];
            }
        }
    }
}

- (void)getAllWantCamera:(NSArray *)array andDirection:(DirectionType)type {
    for (DeviceBaseInfo *model in array) {
        if ((model.DeviceType == 4 && model.Direction == type) || (model.DeviceType == 4 && model.Direction == DirectionTypeUPAndDown)) {
            [_cameraArray addObject:model];
        }
    }
}



- (NSArray *) getTheWantCameraDevice:(NSString *)roadDeretion {
    AppDelegate *myDelegate  = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray = myDelegate.AllDeviceBaseArray ;
    NSMutableArray *wantCameraDevice = [[NSMutableArray alloc] init];
    
    for (DeviceBaseInfo *model in dataSourceArray) {
        if (model.DeviceType == DevicesTypeCamera && (model.Direction == [roadDeretion integerValue] || model.Direction == 3) && [model.RoadUID isEqualToString:_ceModel.RoadUID]) {
            [wantCameraDevice addObject:model];
        }
    }
    return wantCameraDevice;
}

- (NSArray *) getAllCameraGun {
    AppDelegate *myDelegate  = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray = myDelegate.AllDeviceBaseArray ;
    NSMutableArray *wantCameraDevice = [[NSMutableArray alloc] init];
    
    for (DeviceBaseInfo *model in dataSourceArray) {
        if (model.DeviceType == DevicesTypeCamera && [model.RoadUID isEqualToString:_ceModel.RoadUID]) {
            [wantCameraDevice addObject:model];
        }
    }
    return wantCameraDevice;
}

#pragma mark - 显示摄像枪的桩号
- (void)configToolView {
    NSString *beginPileNO = [NSString stringWithFormat:@"%@",_deviceMoel.PileNo];
    NSString *pileDistance = [NSString stringWithFormat:@"%ld",(long)_deviceMoel.PileDistance];
    
    if (_deviceMoel) {
        _cameraGunBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        
        [_cameraGunBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 0)];
        
        if ([_deviceMoel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
            [_cameraGunBtn setTitle:[NSString stringWithFormat:@"%@+%@",beginPileNO, pileDistance] forState:UIControlStateNormal];
        } else {
            NSString *lStr  = @"L";
            NSString *lKStr = [lStr stringByAppendingString:beginPileNO];
            [_cameraGunBtn setTitle:[NSString stringWithFormat:@"%@+%@",lKStr, pileDistance] forState:UIControlStateNormal];
        }
        //        [_cameraGunBtn setTitle:[NSString stringWithFormat:@"%@+%@",beginPileNO, pileDistance] forState:UIControlStateNormal];
        [_cameraGunBtn setTintColor:[UIColor whiteColor]];
        _cameraGunWidth.constant = [self caculateCameraGunBtnWidth] + 25 + 10; // 25 为图片向左偏移量 10为校准值
        [_mapBackGroundView layoutIfNeeded];
        
    }
    if (!_deviceMoel) {
        _cameraGunBtn.hidden = YES;
    }
}

#pragma mark -计算摄像枪按钮的宽度
- (CGFloat ) caculateCameraGunBtnWidth {
    CGSize maxSize   = CGSizeMake(MAXFLOAT, 30);
    CGFloat width = [_cameraGunBtn.titleLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil].size.width;
    return width;
}


#pragma mark -找到最近的摄像枪
- (void) getMostLeastCameraGun {
    NSArray *incidentArray = [_ceModel.BeginPile componentsSeparatedByString:@"K"];
    NSString *incientStr   = incidentArray[1];
    NSInteger incientInter = [incientStr integerValue] * 1000 + [_ceModel.BeginPileDistance integerValue]; //事件
    
    NSMutableArray *intArray = [[NSMutableArray alloc] init];
    
    if (_cameraArray.count == 0) {
        return;
    }
    for (DeviceBaseInfo *model in _cameraArray) {
        
        //        if (model.Direction == [_ceModel.RoadDerection integerValue] ) {
        //            NSArray *strArray = [model.PileNo componentsSeparatedByString:@"K"];
        //            NSString * str = [strArray lastObject];
        //            NSInteger inter = [str integerValue] * 1000 + model.PileDistance;
        NSInteger inter ;
        if (!model.Distance ) {
            inter = 0;
        }else {
            inter = [model.Distance intValue];
        }
        
        NSInteger marginInt = labs(incientInter - inter);
        NSNumber *num       = [NSNumber numberWithInteger:marginInt];
        [intArray addObject:num]; //差值的数组
        //        }
    }
    
    NSNumber *minValue = [intArray valueForKeyPath:@"@min.floatValue"];
    NSUInteger index   = [intArray indexOfObject:minValue];
    
    _deviceMoel = _cameraArray[index]; //最近的摄像枪模型
}

- (void)setEventModel:(EventDetailModel *)eventModel {
    _eventModel = eventModel;
    
    _directionLabel.text = [NSString stringWithFormat:@"%@",_eventModel.EventBaseInfo.RoadDerectionName];
    _beginTimeLabel.text      = _eventModel.EventBaseInfo.OccurTime;
    // 持续时间
    NSDateComponents *com    = [NSDate componentsFrom:_eventModel.EventBaseInfo.OccurTime];
    _lastTimeLabel.text      = [NSString stringWithFormat:@"%ld天%ld小时%ld分",(long)com.day,(long)com.hour,(long)com.minute];
}
#pragma mark - 加载地图事件标注
- (void)loadEventAnnotation { //0.232529--0.300532--11.526650--24.709414--113.471923--326.931946
    
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    NSArray *pileArray =  myDelegate.PirArray;
    NSString *pileStr  = _ceModel.BeginPile;
    for (PileInfo *pileModel in pileArray) {
        if ([pileStr isEqualToString: pileModel.PileNo] && [pileModel.RoadUID isEqualToString:_ceModel.RoadUID]) {
            _ceModel.Latitude = [NSString stringWithFormat:@"%f",pileModel.Latitude];
            _ceModel.Longitude =[NSString stringWithFormat:@"%f", pileModel.Longitude];
        }
    }
    ROPointAnnotation *roAnnotation = [[ROPointAnnotation alloc] init];
    float latitude = [_ceModel.Latitude floatValue];
    float longitude = [_ceModel.Longitude floatValue];
    
    MACoordinateSpan  span                  = MACoordinateSpanMake(0.232529, 0.300532);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
    MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
    _mapView.region           = region;
    
    [_mapView setCenterCoordinate:centerCoordinate animated:NO];
    _mapView.zoomLevel = 11.214808;
    
    CLLocationCoordinate2D ret = CLLocationCoordinate2DMake(latitude, longitude);
    roAnnotation.coordinate = ret;
    _ceModel.Latitude = [NSString stringWithFormat:@"%f",ret.latitude];
    _ceModel.Longitude = [NSString stringWithFormat:@"%f",ret.longitude];
    roAnnotation.currentEventModel = _ceModel;
    [_mapView addAnnotation:roAnnotation];
    
}
#pragma mark - 判断摄像枪
- (void)showshorTestDistanceCameraGun {
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray=myDelegate.AllDeviceBaseArray ;
    if (dataSourceArray.count == 0) return;
    NSMutableArray *distanceArray = [[NSMutableArray alloc] init];//存放在区域内的摄像枪点
    CGFloat latitude = [_ceModel.Latitude floatValue];
    CGFloat longtitude = [_ceModel.Longitude floatValue];
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake(latitude, longtitude);
    MAMapPoint incidentPoint = MAMapPointForCoordinate(coordinate2D);//事件在地图上的所在点
    for (DeviceBaseInfo *baseInfoModel in dataSourceArray) {
        CLLocationCoordinate2D ret = AMapCoordinateConvert(CLLocationCoordinate2DMake(baseInfoModel.Latitude, baseInfoModel.Longitude), AMapCoordinateTypeGPS);
        MAMapPoint point = MAMapPointForCoordinate(ret);
        CLLocationDistance distance = MAMetersBetweenMapPoints(incidentPoint,point);
        NSLog(@"%f",distance);
        NSNumber *number = [NSNumber numberWithDouble:distance];
        [distanceArray addObject:number];
    }
    if (distanceArray == nil) return ;
    
    NSNumber *min = [distanceArray valueForKeyPath:@"@min.doubleValue"] ;
    NSInteger index = [distanceArray indexOfObject:min];
    _minDistanceCamera = dataSourceArray[index];
}

#pragma mark -地图代理
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
        annotationView.calloutView.hidden = YES;
        annotationView.image = [UIImage imageNamed:@"accident_icon"];// 事故图标
        annotationView.centerOffset = CGPointMake(0, -annotationView.image.size.height / 2);
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    CustomAnnotationView *customView = (CustomAnnotationView *)view;
    if (customView.CEModel) {
        customView.selected       = NO;
        customView.canShowCallout = NO;
    }
    customView.calloutView.hidden = YES;
}

-(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    NSLog(@"%f--%f--%f--%f--%f--%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta,mapView.zoomLevel,mapView.region.center.latitude,mapView.region.center.longitude, mapView.rotationDegree);
}


@end
